# -*- coding: cp1252 -*-
import random
import string

from xmpp import *
from Queue import *
import Behaviour
import ACLParser
import Envelope
import ACLMessage
import BasicFipaDateTime
import XMLCodec
import DF
import Organization
import AID

class Flat(Organization.Organization):
    def __init__(self,agent, nick, name,password=None, goalList=[], agentList=[],contentLanguage="sl",create=True):
        Organization.Organization.__init__(self,agent, nick, name, "Flat", goalList, agentList, contentLanguage,create)


    def requestEntryUnit(self,unit,desc=None):
      if self.state=="unavailable":
          raise Organization.Unavailable
          return
      if unit not in self.getUnitList():
          raise Organization.NotValidUnit
          return
      #consultar en el DF quien es el owner de la organización
      dad = DF.DfAgentDescription()
      ds = DF.ServiceDescription()
      ds.setType("UNIT")
      ds.setName(unit)
      dad.addService(ds)
      search = self.myAgent.searchService(dad)
      if search:
          owner=search[0].getAID()
          #comportammiento con mensaje ACL solicitando permiso
          ID="".join([string.ascii_letters[int(random.randint(0,len(string.ascii_letters)-1))] for a in range(5)])
          template = Behaviour.ACLTemplate()
          template.setSender(owner)
          template.setPerformative("inform")
          template.setOntology("spade:x:unit")
          template.setProperty("from",unit)
          template.setConversationId(ID)
          t = Behaviour.MessageTemplate(template)
          self.setTemplate(t)
          b=self.RequestEntryBehaviour(owner,unit,desc,ID)
          self.myAgent.addBehaviour(b, t)
          b.join()
          return b.result

    class RequestEntryBehaviour(Behaviour.OneShotBehaviour):
        def __init__(self,owner,roomname,desc,ID):
            Behaviour.OneShotBehaviour.__init__(self)
            self.owner=owner
            self.name=roomname
            self.desc=desc
            self.ID=ID
            self.result=False

        def _process(self):
            msg=ACLMessage.ACLMessage()
            desc={}
            desc["main"]="Entry"
            if self.desc:
                desc["desc"]=self.desc
            msg.setContent(str(desc))
            msg.setPerformative("request")
            msg.setOntology("spade:x:unit")
            if (msg.getSender() == None):
                msg.setSender(self.myAgent.getAID())
            msg.addReceiver(self.owner)
            msg.setProperty("from",self.name)
            msg.setConversationId(self.ID)
            self.myAgent.send(msg)
            ans= self._receive(True,30)
            if ans:
                if "Allowed:" in ans.getContent():
                   self.result=ans.getContent().split(":")[1]


    def setGoal(self,goalList):
        """
        Updates organization goals
        """
        if self.state=="unavailable":
            raise Organization.Unavailable
            return
        Organization.Organization.setGoal(self,goalList)


##

    def checkCreationPermission(self):
        #QUITAR
        print self.getOwner()
        return True



    def destroy(self):
        if self.state=="unavailable":
            raise Organization.Unavailable
            return
        if not self.owner:
            raise Organization.NotAllowed
            return
        Organization.Organization.destroy(self)




